﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class NektarLinker : MonoBehaviour {
	
	[SerializeField]
	private List<Transform> _links;
	
	[SerializeField]
	private LineRenderer _lineRenderer;
	
	public void AddLink(Transform newTrans)
	{
		if(_links.Count > 0 && _links[_links.Count-1] == newTrans)
		{
			return;
		}
		
		_links.Add(newTrans);
			
		if(_links.Count == 2)
		{
			// destroy the two enemies, spawn nektar!
			StartCoroutine(KillAffected());
		}		
	}
	
	private void Awake()
	{
		_lineRenderer = gameObject.GetComponent<LineRenderer>();
	}
	
	// Use this for initialization
	void Start () {
		
		
	
	}
	
	private IEnumerator KillAffected()
	{
		yield return new WaitForSeconds(1.0f);
		Instantiate(Resources.Load("Prefabs/NektarPickup") as GameObject, _links[0].position, Quaternion.identity);
		Instantiate(Resources.Load("Prefabs/NektarPickup") as GameObject, _links[1].position, Quaternion.identity);
		
		_links[0].GetComponent<Dragonfly>().Kill();
		_links[1].GetComponent<Dragonfly>().Kill();
		
		GameObject.FindGameObjectWithTag("player").GetComponent<Controller>().AddKill();
		GameObject.FindGameObjectWithTag("player").GetComponent<Controller>().AddKill();
		Destroy(gameObject);
		yield return null;
	}
	
	// Update is called once per frame
	void Update ()
	{
		UpdateLine();
	}
	
	private void UpdateLine()
	{
		if(_links.Count > 0 && _links[0] == null)
			Destroy(gameObject);
		
		_lineRenderer.SetVertexCount(_links.Count);
		for(int i = 0; i < _links.Count; i++)
		{
			_lineRenderer.SetPosition(i, _links[i].position);
		}
	}
}
